import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import type { ICurrentUser } from '@nbase/shared';

/**
 * 获取当前登录用户装饰器
 *
 * @example
 * // 获取完整用户对象
 * async getProfile(@CurrentUser() user: ICurrentUser) { ... }
 *
 * // 只获取用户 ID
 * async getPosts(@CurrentUser('userId') userId: string) { ... }
 *
 * // 只获取用户名
 * async doSomething(@CurrentUser('username') username: string) { ... }
 */
export const CurrentUser = createParamDecorator(
  (data: keyof ICurrentUser | undefined, ctx: ExecutionContext): ICurrentUser | string | string[] | undefined => {
    const request = ctx.switchToHttp().getRequest();

    // 从 request.user 获取
    // request.user 由 JwtStrategy.validate() 设置
    const user: ICurrentUser | undefined = request.user;

    if (!user) {
      return undefined;
    }

    if (data) {
      return user[data];
    }

    return user;
  }
);

